package com.m3839.sdk.login.core;

import android.app.Activity;

import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.core.SdkConfiguration;
import com.m3839.sdk.common.event.SubjectBus;
import com.m3839.sdk.common.util.ConditionUtils;
import com.m3839.sdk.login.bean.GameConfig;
import com.m3839.sdk.login.listener.HykbInitListener;
import com.m3839.sdk.login.model.api.IInitModel;
import com.m3839.sdk.login.model.InitApiModel;
import com.m3839.sdk.login.ui.controller.IInitUiController;
import com.m3839.sdk.login.ui.controller.InitUiControllerImpl;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author ChenBaoyang
 * @description: InitManager，初始化游戏信息的管理，只做一件事情，加载初始化配置信息
 * @date 2021/11/12 16:23
 */
public class InitManager {

    /**
     * 是否初始化成功
     */
    private final AtomicBoolean isInitSucceed = new AtomicBoolean(false);

    private HykbInitListener listener;

    private Activity activity;

    private GameConfig initConfig;

    private final IInitModel initModel;
    private final IInitUiController initUiController;

    private InitManager() {
        initModel = new InitApiModel();
        initUiController = new InitUiControllerImpl();
    }

    /**
     * 返回HykbInitManager对象
     */
    public static InitManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final InitManager INSTANCE = new InitManager();
    }


    /**
     * sdk初始化
     */
    public void initConfig(final Activity context, String gameId, int orientation, final HykbInitListener listener) {
        this.activity = context;
        this.listener = listener;

        // 常见通用的过滤条件
        if(!ConditionUtils.commonCondition(activity, new ConditionUtils.ConditionCallback() {
            @Override
            public void callback(int code, String message) {
                // 通用条件的回调
                handleInitCallBackFailed(code, message);
            }
        })){
            return;
        }

        if(isInitOk()) {
            //初始化成功后，限制重复初始化
            if(listener != null) {
                listener.onInitSuccess();
            }
            return;
        }

        // 缓存全局的参数配置信息，尽量早进行初始化
        SdkConfiguration.init(context, gameId, orientation);

        // 初始化数据成功
        observeInitOk();

        // 游戏维护的监听
        observeInitMaintenance();

        // 初始化失败监听
        observeInitFailed();

        // 初始化接口请求
        initModel.loadGameConfig();

    }

    /**
     * 初始化数据成功
     */
    private void observeInitOk() {
        SubjectBus.get().observe(Constant.HYKB_EVENT_INIT, new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                //初始化配置
                initConfig = (GameConfig) arg;
                isInitSucceed.set(true);
                handleInitCallBackSuccess();
            }
        });
    }

    /**
     * 初游戏维护的监听
     */
    private void observeInitMaintenance() {
        SubjectBus.get().observe(Constant.HYKB_EVENT_MAINTENANCE, new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                isInitSucceed.set(false);
                if (activity != null && arg!= null) {
                    initUiController.showMaintenanceDialog(activity,
                            ((GameConfig)arg).getMaintainContent());
                }
            }
        });
    }

    /**
     * 初始化失败监听
     */
    private void observeInitFailed() {
        SubjectBus.get().observe(Constant.HYKB_EVENT_INIT_FAILED, new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                isInitSucceed.set(false);
                //返回初始化错误信息给游戏
                ApiError apiError = (ApiError) arg;
                handleInitCallBackFailed(apiError.code, apiError.message);
            }
        });
    }

    public void handleInitCallBackSuccess() {
        if (listener != null) {
            listener.onInitSuccess();
        }
    }

    public void handleInitCallBackFailed(final int code, final String message) {
        if (listener != null) {
            listener.onInitFailed(code, message);
        }
    }

    /**
     * 是否初始化成功
     *
     * @return
     */
    public boolean isInitOk() {
        return isInitSucceed.get() && listener != null;
    }

    public void reset() {
        isInitSucceed.set(false);
    }

    public void release() {
        reset();
        SubjectBus.get().release();
    }

    public GameConfig getInitConfig(){
        return initConfig;
    }

}
